package org.xxpay.pay.channel.saaspay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.RefundOrderRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.common.util.RandomStrUtils;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.RefundOrder;
import org.xxpay.pay.channel.BaseRefund;
import org.xxpay.pay.channel.wxpay.WxpayRefundService;

import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

import static org.xxpay.pay.channel.saaspay.SaaspayUtil.*;

/**
 * Saas支付
 * @author: Zhixin
 * @date: 2024年3月01日09:07:38
 */
@Service
public class SaaspayRefundService extends BaseRefund {

    private static final MyLog _log = MyLog.getLog(SaaspayRefundService.class);
    String url = "https://api-mop.chinaums.com/v1/netpay/refund";
    String testUrl = "https://test-api-open.chinaums.com/v1/netpay/refund";
    @Override
    public String getChannelName() {
        return SaaspayConfig.CHANNEL_NAME;
    }


    public JSONObject refund(RefundOrder refundOrder) {
        String logPrefix = getChannelName() + "订单退款";
        SaaspayConfig saaspayConfig = new SaaspayConfig(getRefundParam(refundOrder));
//        RefundOrderRes retObj = ApiBuilder.buildSuccess(RefundOrderRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        String refundOrderId = refundOrder.getRefundOrderId();
        JSONObject retObj = buildRetObj();
        retObj.put("refundOrderId", refundOrderId);
        retObj.put("isSuccess", false);
        //1. 组建请求报文
        SaaspayUtil.H5PayRefundBody reqBody = new SaaspayUtil.H5PayRefundBody();
        reqBody.requestTimestamp = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
        reqBody.merOrderId = refundOrder.getPayOrderId();
        reqBody.mid = saaspayConfig.getMid();
        reqBody.tid = saaspayConfig.getTid();
        reqBody.instMid = saaspayConfig.getInstMid();
        reqBody.refundAmount = refundOrder.getRefundAmount()+"";
        System.out.println(refundOrder.getRefundOrderId());
        reqBody.refundOrderId = "386B"+refundOrder.getRefundOrderId();
        System.out.println("request body:\n"+reqBody);
        String nonce = RandomStrUtils.getInstance().getRandomString();
        String requestTime = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSS);

        //2. 获取认证报文，timestamp为当前日期，老旧日期无法请求成功
        String authorization = SaaspayUtil.getAuthorization(saaspayConfig.getAppId(),saaspayConfig.getAppKey(),requestTime,nonce,reqBody.toString());
        System.out.println("authorization:\n"+authorization);
        String reqUrl = url;
        //3. 发送http请求，并解析返回信息
        String response = SaaspayUtil.queryRequest(reqUrl,authorization,reqBody.toString());
        System.out.println("response:\n"+response);
        JSONObject jsonObj = JSON.parseObject(response);

        //4. 解析退款结果并更改订单状态
        if("SUCCESS".equals(jsonObj.getString("errCode"))){
            //更新支付状态并修改商户余额
            retObj.put("isSuccess", true);
            retObj.put("channelOrderNo", jsonObj.getString("merOrderId"));
            commonService.payOrderService.updateStatus4Refund(refundOrder.getPayOrderId());
        }else{
            _log.info("{}返回失败", logPrefix);
            _log.info("sub_code:{},sub_msg:{}", jsonObj.getString("errCode"), jsonObj.getString("errMsg"));
            retObj.put("channelErrCode", jsonObj.getString("errCode"));
            retObj.put("channelErrMsg", jsonObj.getString("errMsg"));
        }
        //5. 组装返回结果
//        JSONObject resObj = buildRetObj();
//        resObj.put("refund_res_status",jsonObj.getString("errCode"));
//        resObj.put("refund_res_detail",jsonObj.getString("errMsg"));
        return retObj;

    }

    /**
     * 查询退款订单
     *
     * @param refundOrder
     * @return
     */
    @Override
    public JSONObject query(RefundOrder refundOrder) {
        String logPrefix = "[" + getChannelName() + "主动查单]";
        SaaspayConfig saaspayConfig = new SaaspayConfig(getRefundParam(refundOrder));
        SaaspayUtil.QueryBody reqBody = new SaaspayUtil.QueryBody();
        JSONObject retObj = buildRetObj();
        retObj.put("refundOrderId", refundOrder.getRefundOrderId());
        //1. 组建请求报文
        reqBody.requestTimestamp = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
        reqBody.merOrderId = "386B"+refundOrder.getRefundOrderId();
        reqBody.mid = saaspayConfig.getMid();
        reqBody.tid = saaspayConfig.getTid();
        reqBody.instMid = saaspayConfig.getInstMid();
        String nonce = RandomStrUtils.getInstance().getRandomString();
        String requestTime = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSS);
        _log.info("{}request body:\n{}", logPrefix, reqBody);
        //2. 获取认证报文，timestamp为当前日期，老旧日期无法请求成功
        String authorization = SaaspayUtil.getAuthorization(saaspayConfig.getAppId(), saaspayConfig.getAppKey(), requestTime, nonce, reqBody.toString());
        _log.info("{}authorization:\n{}", logPrefix, authorization);
        //3. 发送http请求，并解析返回信息
        String queryUrl = saaspayConfig.getReqUrl() + "/refund-query";
        String response = queryRequest(queryUrl, authorization, reqBody.toString());
        System.out.println(response);
//        if(response.isSuccess()){
//            retObj.putAll((Map) JSON.toJSON(response));
//            retObj.put("isSuccess", true);
//        }else {
//            _log.info("{}返回失败", logPrefix);
//            _log.info("sub_code:{},sub_msg:{}", response.getSubCode(), response.getSubMsg());
//            retObj.put("channelErrCode", response.getSubCode());
//            retObj.put("channelErrMsg", response.getSubMsg());
//        }
        _log.info("{}response:\n{}", logPrefix, response);
        return retObj;  //支付中
    }

    public static void main(String[] args) throws Exception {

        String appid = "10037e6f6a4e6da4016a670fd4530012";
        String appkey = "f7a74b6c02ae4e1e94aaba311c04acf2";
        String url = "https://test-api-open.chinaums.com/v1/netpay/refund";
        String testUrl = "https://test-api-open.chinaums.com/v1/netpay/refund";

        //1. 组建请求报文
        String nonce = RandomStrUtils.getInstance().getRandomString();
        String requestTime = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSS);
        SaaspayUtil.H5PayRefundBody reqBody = new SaaspayUtil.H5PayRefundBody();
        reqBody.requestTimestamp = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
        reqBody.merOrderId = "T20240321110322";
        reqBody.mid = "898201612345678";
        reqBody.tid = "88880001";
        reqBody.instMid = "H5DEFAULT";
        reqBody.refundAmount = "1";
        System.out.println("request body:\n" + reqBody);

        //2. 获取认证报文

        String authorization = getAuthorization(appid, appkey, requestTime, nonce, reqBody.toString());
        System.out.println(authorization);
        String refundResult = refundRequest(testUrl,authorization,reqBody.toString());
        System.out.println(refundResult);
    }
}
